package com.seeyon.apps.kk.manager;

import java.rmi.RemoteException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.axis2.AxisFault;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.kk.manager.datasync.AbstractDataSyncManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.v3x.services.form.FormFactory;
import com.seeyon.v3x.services.form.FormUtils;
import com.seeyon.v3x.services.form.bean.FormExport;

import nc.itf.ly_ext.webservice.isyncservice.ISyncServiceStub;
import nc.itf.ly_ext.webservice.isyncservice.ISyncServiceStub.SyncSuppliers;
import nc.itf.ly_ext.webservice.isyncservice.ISyncServiceStub.SyncSuppliersResponse;
import nc.itf.ly_ext.webservice.isyncservice.ISyncServiceStub.SyncWorkType;
import nc.itf.ly_ext.webservice.isyncservice.ISyncServiceStub.SyncWorkTypeResponse;
import nc.itf.ly_ext.webservice.lyandoabuttservice.LyAndOAButtServiceStub;
import nc.itf.ly_ext.webservice.lyandoabuttservice.LyAndOAButtServiceStub.EquipSync;
import nc.itf.ly_ext.webservice.lyandoabuttservice.LyAndOAButtServiceStub.EquipSyncResponse;

/**
 * 资产卡片数据同步
 * 
 * @author seeyon
 *
 */
public class AssetCardSyncManagerImpl extends AbstractDataSyncManager {

	private static final Log log = LogFactory.getLog(AssetCardSyncManagerImpl.class);

	private FreemarkFlowManager freemarkFlowManager;

	public FreemarkFlowManager getFreemarkFlowManager() {
		return freemarkFlowManager;
	}

	public void setFreemarkFlowManager(FreemarkFlowManager freemarkFlowManager) {
		this.freemarkFlowManager = freemarkFlowManager;
	}

	/**
	 * 资产卡片数据初始化
	 */
	public void dataInit() {
		try {
			LyAndOAButtServiceStub stub = new LyAndOAButtServiceStub();
			EquipSync equipSync0 = new EquipSync();
			// 接口增量测试
			String dateSql = this.freemarkFlowManager
					.fltTemplateIntoString("datasync/zichankapian/ZCKP_DATASYNC_MAXDATESQL.ftl", null); // 获取底表最近一次更新时间
			List<Map<String, Object>> maxDate = this.jdbcTemplate.queryForList(dateSql);
			if(!maxDate.isEmpty()){
				Map<String, Object> maxDateMap = maxDate.get(0);
				Map<String, Object> par = new HashMap<>();
				par.put("ts", MapUtils.getString(maxDateMap, "ts"));
				equipSync0.setString(JSON.toJSONString(par));
				log.info("=================>测量:请求参数："+JSON.toJSONString(par));
			}
			EquipSyncResponse rs = stub.equipSync(equipSync0);
			JSONObject jsonObject = JSONObject.parseObject(rs.get_return());
			JSONArray items = JSON.parseArray(jsonObject.getString("obj"));
			log.info("=================>测量:请求数据："+items.toJSONString());
			for (Object object : items) {
				Map<String, Object> map = (Map<String, Object>) object;
				map.put("category_name", MapUtils.getString(map, "fn")); // 
				String flagSql = this.freemarkFlowManager.fltTemplateIntoString("datasync/zichankapian/ZCKP_INIT_DELETESQL.ftl", map);
				List<Map<String, Object>> flagList = this.jdbcTemplate.queryForList(flagSql);
				if (flagList.isEmpty()) {
					String insertSql = this.freemarkFlowManager.fltTemplateIntoString("datasync/zichankapian/ZCKP_INIT_INSERTSQL.ftl", map);
					this.jdbcTemplate.update(insertSql);
				} else {
					String deleteSql = this.freemarkFlowManager.fltTemplateIntoString("datasync/zichankapian/ZCKP_DATASYNC_UPDATESQL.ftl", map);
					this.jdbcTemplate.update(deleteSql);
				}
			}
		} catch (AxisFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.info("=================NC接口调用错误===================\n" + e.getMessage());
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.info("=================NC远程对象引用异常================\n" + e.getMessage());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.info("=================OA调用接口异常================\n" + e.getMessage());
		}

	}

	public void insertData() {
		try {
			String insertSqlDB = this.freemarkFlowManager
					.fltTemplateIntoString("datasync/zichankapian/ZCKP_DATASYNC_ADDSQL.ftl", null);
			List<Map<String, Object>> items = this.jdbcTemplate.queryForList(insertSqlDB);
			for (Map<String, Object> map : items) {
				/*
				 * String status = MapUtils.getString(map, "status_name"); //
				 * 显示状态 枚举 ID 在用、故障、封存、报废 String statusId =
				 * "156163798930443101"; switch (status) { case "故障": statusId =
				 * "306168093548957230"; break; case "封存": statusId =
				 * "-1090043098319598580"; break; case "报废": statusId =
				 * "4773567617570917935"; break; }
				 */
				String categoryName = MapUtils.getString(map, "category_name");
				String categoryId = "";
				if(categoryName != null){
					if(categoryName.equals("A")){
						categoryId =  "-4107566061101563005";
					}else if(categoryName.equals("B")){
						categoryId =  "7984315777146963608";
					}else if(categoryName.equals("C")){
						categoryId =  "-7126080319263061246";
					}
				}
				map.put("category_name", categoryId); // 设备分类
				map.put("status_name", MapUtils.getString(map, "statusName")); 
				String dataXML = this.freemarkFlowManager.fltTemplateIntoString("datasync/XML/addAssetCardXML.ftl",
						map);
				log.info("========测量设备数据添加："+map);
				// 可以使用数据模板生成，这样底表事件依然有效
				FormFactory formFactory = (FormFactory) AppContext.getBean("formFactory");
				FormExport[] formExports = FormUtils.xmlTransformFormExports(dataXML);
				for (FormExport formExport : formExports) {
					formFactory.importBusinessFormData("oa2", "SH_CLSB_DB_001", formExport, null);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("============资产卡片数据添加错误！=============\n" + e.getMessage());
		}

	}
	
	/**
	 * 资产卡片数据更新
	 */
	public void updData(){
		String updSqlDB = this.freemarkFlowManager
				.fltTemplateIntoString("datasync/zichankapian/ZCKP_DATASYNC_UPDSQL.ftl", null);
		List<Map<String, Object>> items = this.jdbcTemplate.queryForList(updSqlDB);
		try {
			for (Map<String, Object> map : items) {
				String update = this.freemarkFlowManager.fltTemplateIntoString("datasync/zichankapian/ZCKP_DATA_UPDSQL.ftl", map);
				log.info("SQL:"+update);
				int count = this.jdbcTemplate.update(update);
				log.info("资产数据更新："+MapUtils.getString(map, "equip_code")+",条，"+count);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.info("=================资产数据更新================\n" + e.getMessage());
		}
	}
	
	/**
	 *  供应商数据同步
	 */
	public void addSupplier(){
		try {

			ISyncServiceStub stub = new ISyncServiceStub();
			SyncSuppliers syncSuppliers14 = new SyncSuppliers();
			SyncSuppliersResponse  rs  =stub.syncSuppliers(syncSuppliers14 ); 
			String dateSql = this.freemarkFlowManager
					.fltTemplateIntoString("datasync/supplie/SELECT_SUPPLIE_MAX_SQL.ftl", null); // 获取底表最近一次更新时间
			List<Map<String, Object>> maxDate = this.jdbcTemplate.queryForList(dateSql);
			if(!maxDate.isEmpty()){
				Map<String, Object> maxDateMap = maxDate.get(0);
				Map<String, Object> par = new HashMap<>();
				par.put("ts", MapUtils.getString(maxDateMap, "ts"));
				syncSuppliers14.setString(JSON.toJSONString(par));
			}
			JSONObject jsonObject = JSONObject.parseObject(rs.get_return());
			JSONArray items = JSON.parseArray(jsonObject.getString("obj"));
			for (Object object : items) {
				Map<String, Object> map = (Map<String, Object>) object;
				if(MapUtils.getString(map, "dr").equals("0")){
				
					String flagSql = this.freemarkFlowManager.fltTemplateIntoString("datasync/supplie/SELECT_SUPPLIE_SQL.ftl", map);
					List<Map<String, Object>> flagList = this.jdbcTemplate.queryForList(flagSql);
					if (flagList.isEmpty()) {
						// 添加数据
						String dataXML = this.freemarkFlowManager.fltTemplateIntoString("datasync/XML/addSupplieXML.ftl", map);
						// 可以使用数据模板生成，这样底表事件依然有效
						FormFactory formFactory = (FormFactory) AppContext.getBean("formFactory");
						FormExport[] formExports = FormUtils.xmlTransformFormExports(dataXML);
						for (FormExport formExport : formExports) {
							formFactory.importBusinessFormData("oa3", "SH_SUPPLIE_001", formExport, null);
						}
						log.info("=======添加供应商底表数据："+map);
					} else {
						String deleteSql = this.freemarkFlowManager.fltTemplateIntoString("datasync/supplie/SELECT_SUPPLIE_UPDATE_SQL.ftl", map);
						int count =  this.jdbcTemplate.update(deleteSql);
						log.info("=======添加供应商底表数据："+count+"条，"+map);
					}
				}
			}
			String deleteSql = this.freemarkFlowManager.fltTemplateIntoString("datasync/supplie/SELECT_SUPPLIE_DELETE_SQL.ftl", null);
			int delCount = this.jdbcTemplate.update(deleteSql);
			log.info("=============删除供应商底表数据："+delCount+"条！");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.info("=================》供应商数据同步错误："+e.getMessage());
		}
	}
	
	/**
	 *  工种数据同步
	 */
	public void addWorkType(){
		try {
			ISyncServiceStub stub = new ISyncServiceStub();
			SyncWorkType syncWorkType16 = new SyncWorkType();
			SyncWorkTypeResponse rs  =stub.syncWorkType(syncWorkType16); 
			String dateSql = this.freemarkFlowManager
					.fltTemplateIntoString("datasync/supplie/SELECT_SUPPLIE_MAX_SQL.ftl", null); // 获取底表最近一次更新时间
			List<Map<String, Object>> maxDate = this.jdbcTemplate.queryForList(dateSql);
			if(!maxDate.isEmpty()){
				Map<String, Object> maxDateMap = maxDate.get(0);
				Map<String, Object> par = new HashMap<>();
				par.put("ts", MapUtils.getString(maxDateMap, "ts"));
				syncWorkType16.setString(JSON.toJSONString(par));
			}
			JSONObject jsonObject = JSONObject.parseObject(rs.get_return());
			JSONArray items = JSON.parseArray(jsonObject.getString("obj"));
			for (Object object : items) {
				Map<String, Object> map = (Map<String, Object>) object;
				if(MapUtils.getString(map, "dr").equals("0")){
				
					String flagSql = this.freemarkFlowManager.fltTemplateIntoString("datasync/supplie/SELECT_SUPPLIE_SQL.ftl", map);
					List<Map<String, Object>> flagList = this.jdbcTemplate.queryForList(flagSql);
					if (flagList.isEmpty()) {
						// 添加数据
						String dataXML = this.freemarkFlowManager.fltTemplateIntoString("datasync/XML/addWorkTypeXML.ftl", map);
						// 可以使用数据模板生成，这样底表事件依然有效
						FormFactory formFactory = (FormFactory) AppContext.getBean("formFactory");
						FormExport[] formExports = FormUtils.xmlTransformFormExports(dataXML);
						for (FormExport formExport : formExports) {
							formFactory.importBusinessFormData("oa3", "SH_WORK_TYPE_001", formExport, null);
						}
						log.info("=======添加工种数据："+map);
					} else {
						String deleteSql = this.freemarkFlowManager.fltTemplateIntoString("datasync/supplie/SELECT_SUPPLIE_UPDATE_SQL.ftl", map);
						int count =  this.jdbcTemplate.update(deleteSql);
						log.info("=======添加工种底表数据："+count+"条，"+map);
					}
				}
			}
			String deleteSql = this.freemarkFlowManager.fltTemplateIntoString("datasync/supplie/SELECT_SUPPLIE_DELETE_SQL.ftl", null);
			int delCount = this.jdbcTemplate.update(deleteSql);
			log.info("=============删除工种底表数据："+delCount+"条！");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.info("=================》工种数据同步错误："+e.getMessage());
		}
	}


	@Override
	public boolean beforeGrabData() {
		// TODO Auto-generated method stub
		log.info("=================资产卡片数据同步开始============================");
		dataInit();
		insertData();
		updData();
		log.info("=================资产卡片数据同步结束============================");
		log.info("=================供应商、工种数据同步开始============================");
		addSupplier();
		addWorkType();
		log.info("=================供应商、工种数据同步结束============================");
		return false;
	}

	@Override
	public boolean grabData() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean updateData() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean deleteData() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean addData() {
		// TODO Auto-generated method stub
		return false;
	}
}
